import { NextResponse } from 'next/server';
import { sqliteDb } from '@/lib/sqlite-database';

export async function POST() {
  try {
    console.log('开始填充示例位置数据...');
    
    // 获取所有设备
    const devices = sqliteDb.getAllDevices();
    console.log(`找到 ${devices.length} 个设备`);
    
    let updatedCount = 0;
    
    for (const device of devices) {
      if (!device.id) continue;
      
      // 获取该设备的位置参数
      const positionParams = sqliteDb.getPositionParametersByDeviceId(device.id);
      
      // 根据设备专业和名称生成真实的位置数据
      const locationData = generateLocationData(device);
      
      // 更新位置参数值
      for (const param of positionParams) {
        if (param.id && locationData[param.parameter_name]) {
          sqliteDb.updatePositionParameterValue(param.id, locationData[param.parameter_name]);
          updatedCount++;
        }
      }
      
      // 同时填充一些命名参数的示例数据
      const namingParams = sqliteDb.getNamingParametersByDeviceId(device.id);
      const namingData = generateNamingData(device);
      
      for (const param of namingParams) {
        if (param.id && namingData[param.parameter_name]) {
          sqliteDb.updateNamingParameterValue(param.id, namingData[param.parameter_name]);
          updatedCount++;
        }
      }
      
      // 填充一些基础参数的示例数据
      const baseParams = sqliteDb.getBaseParametersByDeviceId(device.id);
      const baseData = generateBaseData(device);
      
      for (const param of baseParams) {
        if (param.id && baseData[param.parameter_name]) {
          sqliteDb.updateBaseParameterValue(param.id, baseData[param.parameter_name]);
          updatedCount++;
        }
      }
    }
    
    console.log(`示例数据填充完成！更新了 ${updatedCount} 个参数值`);
    
    return NextResponse.json({
      success: true,
      message: `成功填充 ${devices.length} 个设备的示例数据，共更新 ${updatedCount} 个参数值`,
      deviceCount: devices.length,
      updatedCount
    });
    
  } catch (error) {
    console.error('填充示例数据失败:', error);
    return NextResponse.json({
      success: false,
      message: `填充失败: ${error instanceof Error ? error.message : '未知错误'}`
    }, { status: 500 });
  }
}

// 根据设备信息生成位置数据
function generateLocationData(device: any): Record<string, string> {
  const { specialty, name, device_id } = device;
  
  // 根据专业生成不同的位置信息
  const locationTemplates: Record<string, Record<string, string>> = {
    '配管专业': {
      '装置名称': getProcessUnit(name),
      '系统名称': getPipingSystem(name),
      '位置描述': getPipingLocation(name, device_id)
    },
    '仪表专业': {
      '装置名称': getProcessUnit(name),
      '系统名称': getInstrumentSystem(name),
      '位置描述': getInstrumentLocation(name, device_id)
    },
    '电气专业': {
      '装置名称': getElectricalUnit(name),
      '系统名称': getElectricalSystem(name),
      '位置描述': getElectricalLocation(name, device_id)
    },
    '通信专业': {
      '装置名称': '控制室',
      '系统名称': getCommunicationSystem(name),
      '位置描述': getCommunicationLocation(name, device_id)
    },
    '暖通专业': {
      '装置名称': 'HVAC系统',
      '系统名称': getHvacSystem(name),
      '位置描述': getHvacLocation(name, device_id)
    }
  };
  
  return locationTemplates[specialty] || {
    '装置名称': '主装置',
    '系统名称': '公用系统',
    '位置描述': `${name}安装位置 (${device_id})`
  };
}

// 生成命名参数数据
function generateNamingData(device: any): Record<string, string> {
  const { name, device_id } = device;
  
  return {
    '设备位号': device_id,
    '设备名称': name,
    '设备规格': getDeviceSpec(name)
  };
}

// 生成基础参数数据
function generateBaseData(device: any): Record<string, string> {
  const { name } = device;
  
  return {
    '额定流量': getFlowRate(name),
    '额定压力': getPressure(name),
    '额定功率': getPower(name)
  };
}

// 辅助函数：根据设备名称生成工艺装置
function getProcessUnit(name: string): string {
  if (name.includes('消防') || name.includes('应急')) return '消防系统装置';
  if (name.includes('给水') || name.includes('供水')) return '给水装置';
  if (name.includes('排水') || name.includes('污水')) return '排水装置';
  if (name.includes('储罐') || name.includes('罐')) return '储罐区';
  if (name.includes('泵')) return '泵房装置';
  if (name.includes('管道') || name.includes('管')) return '管网系统';
  return '主工艺装置';
}

// 辅助函数：根据设备名称生成配管系统
function getPipingSystem(name: string): string {
  if (name.includes('消防')) return '消防给水系统';
  if (name.includes('给水') || name.includes('供水')) return '工业给水系统';
  if (name.includes('排水')) return '排水系统';
  if (name.includes('冷却')) return '循环冷却水系统';
  if (name.includes('蒸汽')) return '蒸汽系统';
  if (name.includes('压缩空气')) return '压缩空气系统';
  return '工艺管道系统';
}

// 辅助函数：生成配管位置描述
function getPipingLocation(name: string, deviceId: string): string {
  const area = Math.floor(Math.random() * 5) + 1;
  const elevation = Math.floor(Math.random() * 20) + 10;
  return `工艺区域${area}，标高+${elevation}m，坐标(${deviceId.substring(3)}, ${area * 10}, ${elevation})`;
}

// 辅助函数：生成仪表系统
function getInstrumentSystem(name: string): string {
  if (name.includes('温度') || name.includes('测温')) return '温度检测系统';
  if (name.includes('压力')) return '压力检测系统';
  if (name.includes('流量')) return '流量检测系统';
  if (name.includes('液位')) return '液位检测系统';
  if (name.includes('分析') || name.includes('检测')) return '分析检测系统';
  if (name.includes('控制') || name.includes('调节')) return '过程控制系统';
  if (name.includes('安全') || name.includes('SIS')) return '安全仪表系统';
  return '过程控制系统';
}

// 辅助函数：生成仪表位置描述
function getInstrumentLocation(name: string, deviceId: string): string {
  const unit = Math.floor(Math.random() * 3) + 1;
  const cabinet = Math.floor(Math.random() * 10) + 1;
  return `控制室${unit}，仪表柜${cabinet}号，安装高度1.5m`;
}

// 辅助函数：生成电气装置
function getElectricalUnit(name: string): string {
  if (name.includes('照明') || name.includes('灯')) return '照明系统装置';
  if (name.includes('配电') || name.includes('开关')) return '配电装置';
  if (name.includes('变压器')) return '变电站';
  if (name.includes('接地')) return '接地系统装置';
  return '电气装置';
}

// 辅助函数：生成电气系统
function getElectricalSystem(name: string): string {
  if (name.includes('照明')) return '工艺照明系统';
  if (name.includes('配电')) return '低压配电系统';
  if (name.includes('UPS') || name.includes('EPS')) return '不间断电源系统';
  if (name.includes('接地')) return '电气接地系统';
  return '电力供应系统';
}

// 辅助函数：生成电气位置描述
function getElectricalLocation(name: string, deviceId: string): string {
  const building = Math.floor(Math.random() * 3) + 1;
  const floor = Math.floor(Math.random() * 4) + 1;
  return `电气楼${building}号，${floor}层，电缆沟内，标识牌${deviceId}`;
}

// 辅助函数：生成通信系统
function getCommunicationSystem(name: string): string {
  if (name.includes('视频') || name.includes('监控')) return '视频监控系统';
  if (name.includes('火灾') || name.includes('报警')) return '火灾自动报警系统';
  if (name.includes('门禁') || name.includes('出入')) return '门禁管控系统';
  if (name.includes('广播')) return '公共广播系统';
  return '综合通信系统';
}

// 辅助函数：生成通信位置描述
function getCommunicationLocation(name: string, deviceId: string): string {
  const zone = Math.floor(Math.random() * 6) + 1;
  return `监控中心，第${zone}区域，机柜A${zone}-${deviceId.substring(3)}`;
}

// 辅助函数：生成暖通系统
function getHvacSystem(name: string): string {
  if (name.includes('空调')) return '空调系统';
  if (name.includes('通风')) return '通风系统';
  if (name.includes('供热')) return '供热系统';
  return 'HVAC系统';
}

// 辅助函数：生成暖通位置描述
function getHvacLocation(name: string, deviceId: string): string {
  return `设备机房，屋顶层，坐标(120.5, 85.2, 25.0)`;
}

// 辅助函数：生成设备规格
function getDeviceSpec(name: string): string {
  if (name.includes('泵')) return 'Q=50m³/h, H=32m, N=15kW';
  if (name.includes('阀门')) return 'DN100, PN1.6MPa, 法兰连接';
  if (name.includes('储罐')) return 'V=100m³, P=0.8MPa, 材质SS304';
  if (name.includes('变压器')) return 'SCB-1250/6.3kV, 干式变压器';
  if (name.includes('灯')) return 'LED 36W, IP65, 220V';
  return '按技术规格书要求';
}

// 辅助函数：生成流量参数
function getFlowRate(name: string): string {
  if (name.includes('泵')) {
    const flow = Math.floor(Math.random() * 100) + 20;
    return `${flow}`;
  }
  if (name.includes('阀')) return '50';
  return '';
}

// 辅助函数：生成压力参数
function getPressure(name: string): string {
  if (name.includes('泵') || name.includes('阀')) {
    const pressure = (Math.random() * 2 + 0.5).toFixed(1);
    return pressure;
  }
  return '';
}

// 辅助函数：生成功率参数
function getPower(name: string): string {
  if (name.includes('泵')) {
    const power = Math.floor(Math.random() * 30) + 5;
    return `${power}`;
  }
  if (name.includes('灯')) return '0.036';
  if (name.includes('风机')) return '7.5';
  return '';
} 